package com.example;

import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author linfeng
 * @date 2021/12/27 10:19
 */
public class WeakHashMapTest {

    public static class PojoKey {
        private String name;

        public PojoKey(String name) {
            this.name = name;
        }

        @Override
        protected void finalize() throws Throwable {
            System.out.println("PojoKey [" + name + "] 被回收了");
            super.finalize();
        }
    }

    public static class PojoValue {
        private String name;

        public PojoValue(String name) {
            this.name = name;
        }

        @Override
        protected void finalize() throws Throwable {
            System.out.println("PojoValue [" + name + "] 被回收了");
            super.finalize();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Map<PojoKey, Object> weakHashMap = new WeakHashMap<>();
        weakHashMap.put(new PojoKey("zhangsan"), new PojoValue("张三"));
        // weakHashMap.put(new PojoKey("zhangsan"), new WeakReference(new PojoValue("张三")));
        while (true) {
            TimeUnit.SECONDS.sleep(1);
            System.gc();
            // 如果不加下面这一行，pojoValue不会被回收
            weakHashMap.size();
        }
    }

}
